/**
 * Copyright 2009-2017 the original author or authors.
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.ibatis.scripting.xmltags;

import org.apache.ibatis.parsing.GenericTokenParser;
import org.apache.ibatis.parsing.TokenHandler;
import org.apache.ibatis.scripting.ScriptingException;
import org.apache.ibatis.type.SimpleTypeRegistry;

import java.util.regex.Pattern;

/**
 * @author Clinton Begin
 */
public class TextSqlNode implements SqlNode {
	private final String text;

	private final Pattern injectionFilter;

	public TextSqlNode(String text) {
		this(text, null);
	}

	public TextSqlNode(String text, Pattern injectionFilter) {
		this.text = text;
		this.injectionFilter = injectionFilter;
	}

	public boolean isDynamic() {
		// 判断是否属于动态SQL，当SQL中有${}参数占位符时，即认为属于动态SQL
		DynamicCheckerTokenParser checker = new DynamicCheckerTokenParser();
		GenericTokenParser parser = createParser(checker);
		parser.parse(text);
		return checker.isDynamic();
	}

	@Override
	public boolean apply(DynamicContext context) {
		// 通过GenericTokenParser对象解析${}参数占位符，使用BindingTokenParser对象处理参数占位符内容
		GenericTokenParser parser = createParser(new BindingTokenParser(context, injectionFilter));
		// 调用GenericTokenParser对象的parse（）方法解析
		context.appendSql(parser.parse(text));
		return true;
	}

	private GenericTokenParser createParser(TokenHandler handler) {
		return new GenericTokenParser("${", "}", handler);
	}

	private static class BindingTokenParser implements TokenHandler {

		private DynamicContext context;

		private Pattern injectionFilter;

		public BindingTokenParser(DynamicContext context, Pattern injectionFilter) {
			this.context = context;
			this.injectionFilter = injectionFilter;
		}

		@Override
		public String handleToken(String content) {
			// 获取Mybatis内置参数_parameter，_parameter属性中保存所有参数信息
			Object parameter = context.getBindings().get("_parameter");
			if (parameter == null) {
				context.getBindings().put("value", null);
			} else if (SimpleTypeRegistry.isSimpleType(parameter.getClass())) {
				// 將参数对象添加到ContextMap对象中
				context.getBindings().put("value", parameter);
			}
			// 通过OGNL表达式获取参数值
			Object value = OgnlCache.getValue(content, context.getBindings());
			String srtValue = (value == null ? "" : String.valueOf(value)); // issue #274 return "" instead of "null"
			checkInjection(srtValue);
			// 返回参数值
			return srtValue;
		}

		private void checkInjection(String value) {
			if (injectionFilter != null && !injectionFilter.matcher(value).matches()) {
				throw new ScriptingException("Invalid input. Please conform to regex" + injectionFilter.pattern());
			}
		}
	}

	private static class DynamicCheckerTokenParser implements TokenHandler {

		private boolean isDynamic;

		public DynamicCheckerTokenParser() {
			// Prevent Synthetic Access
		}

		public boolean isDynamic() {
			return isDynamic;
		}

		@Override
		public String handleToken(String content) {
			this.isDynamic = true;
			return null;
		}
	}

}